package face.pay.cpn.cardInfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.cpn.cardInfo.ICpnCardInfoService;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.MathUtil;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.CardAPI;
import weixin.popular.bean.card.create.CreateResult;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Classname CpnCardInfoServiceImpl
 * @Description JJL
 * @Date 2019/12/2 13:41
 */
@Service
@Slf4j
public class CpnCardInfoServiceImpl implements ICpnCardInfoService {


    @Autowired
    private CpnCardInfoDao cpnCardInfoDao;

    @Autowired
    private CpnActivityInfoDao cpnActivityInfoDao;

    @Autowired
    private CpnMchInfoDao cpnMchInfoDao;

    @Autowired
    private CpnMchServiceInfoDao cpnMchServiceInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private CpnMchWorkTimeDao cpnMchWorkTimeDao;

    @Autowired
    private AbstractRedis abstractRedis;

    /**
     * 获取token
     *
     * @return
     */
    private String getAccess_token() {
        String str = (String) this.abstractRedis.get(CacheKey.WX_APP_INFO);
        if (str == null) {
            return null;
        }
        CpnWxAppInfo cpnWxAppInfo = null;
        try {
            cpnWxAppInfo = JSONObject.parseObject(str, CpnWxAppInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return cpnWxAppInfo.getAccess_token();
    }

    /**
     * 编辑卡券信息
     *
     * @param loginUser
     * @param cpnCardInfo
     * @return
     */
    @Override
    public ResultMessage modifyCardInfo(UserInfo loginUser, CpnCardInfo cpnCardInfo) {
        cpnCardInfo.setQuantity(10);
        cpnCardInfoDao.updateCardInfo(cpnCardInfo);
        return ResultMessage.createSuccess();
    }

    /**
     * 制作卡券
     *
     * @param cpnCardInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage startMakeCard(UserInfo loginUser, CpnCardInfo cpnCardInfo) {
        Integer userId = loginUser.getId();

        cpnCardInfo.setUserId(userId);

        CpnCardInfo cardInfo = cpnCardInfoDao.getById(cpnCardInfo); //查询卡券表

        CpnMchInfo cpnMchInfo = new CpnMchInfo();
        cpnMchInfo.setMerchant_id(cardInfo.getMerchant_id());
        CpnMchInfo mchInfo = cpnMchInfoDao.queryCpnMchInfo(cpnMchInfo); //查询商户进件表

        CpnMchServiceInfo cpnMchServiceInfo = new CpnMchServiceInfo();
        cpnMchServiceInfo.setUserId(userId);
        CpnMchServiceInfo mchServiceInfo = cpnMchServiceInfoDao.queryCpnMchServiceInfo(cpnMchServiceInfo); //查询商户服务设置表

        CpnActivityInfo activityInfo = cpnActivityInfoDao.getById(cardInfo.getActivityId()); //查询活动表
        if (activityInfo.getState() == 1) {
            return ResultMessage.createFail("活动已开启，不可制券");
        }

        StoreInfo storeInfo = storeInfoDao.getById(activityInfo.getStoreId()); //查询门店表

        CpnMchWorkTime cpnMchWorkTime = new CpnMchWorkTime();
        cpnMchWorkTime.setMch_user_id(userId);
        cpnMchWorkTime.setStatus(1);
        List<CpnMchWorkTime> cpnMchWorkTimes = cpnMchWorkTimeDao.queryCpnMchWorkTime(cpnMchWorkTime);//营业时间

        log.info("创建优惠券的商户名称：" + mchInfo.getBrand_name());

        Map<String, Object> boss = new HashMap<>();//0层

        Map<String, Object> card = new HashMap<>();//1层
        card.put("card_type", cardInfo.getCard_type());
        log.info("创建优惠券类型：" + cardInfo.getCard_type());

        String card_type = cardInfo.getCard_type().toLowerCase();  //第二层的key 是优惠券类型（card_type）的小写
        Map<String, Object> type = new HashMap<>();//2层
        type.put("discount", MathUtil.multiply(cardInfo.getDiscount(), 100)); //折扣率

        //卡券基础信息
        Map<String, Object> base_info = new HashMap<>();//3层
        base_info.put("logo_url", mchInfo.getLogo_url());
        base_info.put("brand_name", mchInfo.getBrand_name());
        base_info.put("code_type", cardInfo.getCode_type());
        base_info.put("title", cardInfo.getTitle());
        base_info.put("color", cardInfo.getColor());
        base_info.put("notice", cardInfo.getNotice());
        base_info.put("service_phone", mchServiceInfo.getService_phone());
//        base_info.put("center_app_brand_user_name","gh_5dc7b0cfc499@app");  //小程序原始id
//        base_info.put("center_app_brand_pass","pages/index");
//        base_info.put("center_title","立即使用");


        String str = mchServiceInfo.getDescription();
        String description = "使用地址: " + str + "\n" + storeInfo.getProvince() + storeInfo.getCity() + storeInfo.getDistrict() +
                storeInfo.getAddress();  //门店地址+卡券使用说明
        base_info.put("description", description);

        Map<String, Object> sub_merchant_info = new HashMap<>();//4层 商户id
        sub_merchant_info.put("merchant_id", mchInfo.getMerchant_id());
        base_info.put("sub_merchant_info", sub_merchant_info);
        log.info("商户id" + mchInfo.getMerchant_id());

        Map<String, Object> date_info = new HashMap<>();//4层 优惠券使用时间
        date_info.put("type", cardInfo.getType());
        if (cardInfo.getFixed_term() == null) {
            log.info("制券失败，优惠券信息未填写完整!");
            return ResultMessage.createFail("请完善优惠券详细信息!!!");
        }
        date_info.put("fixed_term", cardInfo.getFixed_term());
        date_info.put("fixed_begin_term", cardInfo.getFixed_begin_term());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(activityInfo.getEnd_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime() / 1000; //转为时间戳 秒
        date_info.put("end_timestamp", ts); //统一过期时间

        Map<String, Object> sku = new HashMap<>();//4层 卡券创建数量
        sku.put("quantity", cardInfo.getQuantity());
        log.info("优惠券创建数量：" + cardInfo.getQuantity());

        base_info.put("date_info", date_info);
        base_info.put("sku", sku);
        base_info.put("use_limit", 50);
        base_info.put("get_limit", 50);
        base_info.put("can_share", false);  //卡券领取页面是否可分享
        base_info.put("can_give_friend", false); // 卡券是否可转赠

        //卡券高级信息
        Map<String, Object> advanced_info = new HashMap<>();//3层

        Map<String, Object> use_condition = new HashMap<>();//4层 指定可用商品与不可用商品
        use_condition.put("accept_category", cardInfo.getAccept_category());  //可用商品
        use_condition.put("reject_category", cardInfo.getReject_category());//不可用商品
        use_condition.put("can_use_with_other_discount", false);  // 是否可与其他类型共享门槛
        advanced_info.put("use_condition", use_condition);

        Map<String, Object> abs = new HashMap<>();//4层 封面摘要
        abs.put("abstract", activityInfo.getConver_text());
        String[] icon_url_list = {activityInfo.getIcon_url()};
        abs.put("icon_url_list", icon_url_list);
        advanced_info.put("abstract", abs);

        List<Map<String, Object>> time_limit = new ArrayList<>();//4层 营业时间
        for (CpnMchWorkTime workTime : cpnMchWorkTimes) {
            Map<String, Object> time_limit_map = new HashMap<>();
            time_limit_map.put("type", workTime.getType().toUpperCase());
            time_limit_map.put("begin_hour", workTime.getBegin_hour());
            time_limit_map.put("begin_minute", workTime.getBegin_minute());
            time_limit_map.put("end_hour", workTime.getEnd_hour());
            time_limit_map.put("end_minute", workTime.getEnd_minute());
            time_limit.add(time_limit_map);
        }
        advanced_info.put("time_limit", time_limit);

        if (activityInfo.getImage_url() != null && !activityInfo.getImage_url().isEmpty()) {
            List<Map<String, Object>> text_image_list = new ArrayList<>();
            Map<String, Object> text_image_map = new HashMap<>();//4层 图文简介
            text_image_map.put("image_url", activityInfo.getImage_url());
            text_image_map.put("text", activityInfo.getText());
            text_image_list.add(text_image_map);
            advanced_info.put("text_image_list", text_image_list);
        }

        //商家服务类型
        if (mchServiceInfo.getBusiness_service() != null && !mchServiceInfo.getBusiness_service().isEmpty()) {
            String[] business_service = mchServiceInfo.getBusiness_service().split(",");
            advanced_info.put("business_service", business_service);
        }

        type.put("base_info", base_info);//第二层添加第三次----卡券基础信息
        type.put("advanced_info", advanced_info);//第二层添加第三次----卡券高级信息
        card.put(card_type, type);//第一层添加第二层
        boss.put("card", card); //最外层
        Object json = JSON.toJSON(boss);
        System.out.println(json);
        String access_token = getAccess_token();

        if (access_token == null || access_token.isEmpty()) {
            log.warn("制作卡券时：获取access_token失败!!!!");
            return ResultMessage.createFail("请稍后再试!!!");
        }

        CreateResult createResult = CardAPI.create(access_token, json.toString());
        if (createResult.getCardId() == null) {
            log.warn("微信创卷接口调用失败!错误消息：" + createResult.getErrmsg());
            return ResultMessage.createFail("制作优惠券失败!请与管理员联系!");
        }
        //保存card_id
        cpnCardInfo.setUpdatedBy(cardInfo.getUserId());
        cpnCardInfo.setCard_id(createResult.getCardId());
        cpnCardInfoDao.updateCardId(cpnCardInfo);
        log.info("成功保存card_id:" + createResult.getCardId());

        //制券成功状态为 上线
        cpnCardInfo.setState(1);
        cpnCardInfoDao.updateCardState(cpnCardInfo);
        log.info("卡券id: " + cardInfo.getId() + "状态更改为——上线");

        CpnMchServiceInfo serviceInfo = new CpnMchServiceInfo();
        serviceInfo.setStatus(1);
        serviceInfo.setUserId(mchServiceInfo.getUserId());
        cpnMchServiceInfoDao.update(serviceInfo);
        log.info("上线成功，商家服务设置信息不可修改");

        return ResultMessage.createSuccess();
    }
}
